package com.wac.data.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wac.data.entity.Article;
import com.wac.data.service.ArticleService;
import com.wac.data.service.UserService;
import com.wac.data.utils.DataListUtil;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author beta
 * @since 2023-03-16
 */
@RestController
@RequestMapping("/article")
public class ArticleController {

	private static ObjectMapper objectMapper = new ObjectMapper();

	@Resource
	private ArticleService articleService;
	@Resource
	private UserService userService;

	//发布文章
	@RequestMapping("/issue")
	public String articleIssue(@RequestPart("article") Article article, HttpServletRequest request, @RequestPart("file") List<MultipartFile> file) {
		article.setUserId(userService.isUserLogin(new DataListUtil().getCookies(request)));
		if (articleService.addArticle(article, file)) {
			return "1";
		}
		return "0";
	}

	/**
	 * 获取文章列表 用于首页数据
	 * 输入字段 page 默认 1
	 * 封装返回 cover,title,content,zone,time,commentNum
	 */
	@RequestMapping("/list")
	public String articleListGet(int page) throws JsonProcessingException {
		return objectMapper.writeValueAsString(articleService.getArticle(page));
	}

	//一个文章的详细内容
	@RequestMapping("/one")
	public String getArticleById(String id) throws JsonProcessingException {
		return objectMapper.writeValueAsString(articleService.getArticleById(id));
	}

	@RequestMapping("/delete")
	public String articleDelete(String id) {
		if (articleService.delete(id)) {
			return "1";
		}
		return "0";
	}
}

